﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using AutoWelding.BLL;
using AutoWelding.Models;
using AutoWelding.Utils;

using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace AutoWelding.Views.Recipes
{
    public partial class RecipesForm : Form
    {
        public RecipesForm()
        {
            InitializeComponent();
        }

        private RecipesBLL recipesBLL = new RecipesBLL();
        private ProductsBLL productsBLL = new ProductsBLL();

        private void RecipesForm_Load(object sender, EventArgs e)
        {
            //指定列,进行绑定，不绑定的列不显示。
            dgv_recipesdata.AutoGenerateColumns = false;
            // 初始化 产品名称下拉框数据
            LoadProductsNameData();
            //加载配方数据
            LoadRecipesData();
        }

        /// <summary>
        /// 加载配方数据
        /// </summary>
        private void LoadRecipesData()
        {
            string recipeName = txt_recipeName.Text;
            int productId = Convert.ToInt32(cbx_peoductName.SelectedValue);
            bool isDelete = checkBox_del.Checked;
            //设置 移除、删除、修改按钮是否可见
            if(isDelete)
            {
                btn_del.Visible = false;
                dgv_recipesdata.Columns["col_delete"].Visible = false;
                dgv_recipesdata.Columns["col_update"].Visible = false;
                dgv_recipesdata.Columns["col_recover"].Visible = true;
                dgv_recipesdata.Columns["col_remove"].Visible = true;
            }
            else
            {
                btn_del.Visible = true;
                dgv_recipesdata.Columns["col_delete"].Visible = true;
                dgv_recipesdata.Columns["col_update"].Visible = true;
                dgv_recipesdata.Columns["col_remove"].Visible = false;
                dgv_recipesdata.Columns["col_recover"].Visible = false;
            }

            List<RecipesModel> recipesList = recipesBLL.GetRecipesList(recipeName, productId, isDelete);
            //加载配方信息
            if (recipesList.Count > 0)
            {
                dgv_recipesdata.DataSource = recipesList;
                btn_del.Visible = true;
                //UpdateLinkColumnTexts();
            }
            else
            {
                dgv_recipesdata.DataSource = null;
                btn_del.Visible = false;
            }

        }
        /// <summary>
        /// 初始化 产品名称下拉框数据
        /// </summary>
        private void LoadProductsNameData()
        {
            // 获取产品列表
            List<ProductsModel> productsList = productsBLL.GetProductsList("", false);

            // 创建默认项
            ProductsModel defaultItem = new ProductsModel
            {
                ProductId = 0, // 使用特殊ID表示默认项
                ProductName = "---请选择---"
            };

            // 在列表前面插入默认项
            productsList.Insert(0, defaultItem);

            // 设置数据源
            cbx_peoductName.DataSource = productsList;

            // 设置显示成员（下拉框中显示的文本）
            cbx_peoductName.DisplayMember = "ProductName";

            // 设置值成员（下拉框中每个选项的值）
            cbx_peoductName.ValueMember = "ProductId";

            // 设置默认选中项（可选）
            cbx_peoductName.SelectedIndex = 0;

        }

        /// <summary>
        /// 配方数据表格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgv_recipesdata_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //获取当前单元格
            var cell = dgv_recipesdata.Rows[e.RowIndex].Cells[e.ColumnIndex];
            string headText = cell.FormattedValue.ToString();
            RecipesModel recipesModel = dgv_recipesdata.Rows[e.RowIndex].DataBoundItem as RecipesModel;
            switch (headText)
            {
                case "编辑":
                    ShowRecipeInfoForm(1, recipesModel.RecipeId);
                    break;
                case "删除":
                    if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        if(recipesBLL.LogicDeleteRecipes(new List<int> { recipesModel.RecipeId }))
                        {
                            LoadRecipesData();
                        }
                        else
                            MessageBox.Show("删除失败");
                    }
                    break;
                     
                case "恢复":
                    RecoverRecipe(recipesModel);
                    break;
                case "移除":
                    if(MessageBox.Show("确定永远移除"+recipesModel.RecipeName+"吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (recipesBLL.DeleteRecipe(recipesModel.RecipeId))
                        {
                            MessageBox.Show("移除成功！");
                            LogHelper.Info(this.GetType(), "永久移除" + recipesModel.RecipeName + "成功！");
                            LoadRecipesData();
                        }
                        else
                        {
                            MessageBox.Show("删除失败！");
                        }
                    }
                    break;
                case "查看详情":
                    ShowRecipeInfoForm(0, recipesModel.RecipeId);
                    break;

            }
        }
        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_select_Click(object sender, EventArgs e)
        {
            //加载配方数据
            LoadRecipesData();
        }

        /// <summary>
        /// 删除按钮点击事件（批量删除）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_del_Click(object sender, EventArgs e)
        {
            List<int> selectedRecipeIds = new List<int>();

            try
            {
                // 1️⃣ 遍历表格获取所有选中的 ID
                foreach (DataGridViewRow row in dgv_recipesdata.Rows)
                {
                    var dataBoundItem = row.DataBoundItem as RecipesModel;
                    if (dataBoundItem == null) continue;

                    var checkBoxCell = row.Cells["col_checkBox"] as DataGridViewCheckBoxCell;
                    if (checkBoxCell?.FormattedValue is bool flag && flag)
                    {
                        selectedRecipeIds.Add(dataBoundItem.RecipeId);
                    }
                }
                // 2️⃣ 没有选中任何行
                if (selectedRecipeIds.Count == 0)
                {
                    MessageBox.Show("请先选择要删除的配方！", "提示");
                    return;
                }
                // 3️⃣ 弹出确认框
                if (MessageBox.Show($"确定要删除选中的 {selectedRecipeIds.Count} 个配方吗？", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }
                // 4️⃣ 执行批量删除
                bool result = recipesBLL.LogicDeleteRecipes(selectedRecipeIds);

                if (result)
                {
                    LogHelper.Info(this.GetType(), $"成功删除 {selectedRecipeIds.Count} 个配方。");
                    LoadRecipesData(); // 刷新列表
                }
                else
                {
                    MessageBox.Show("删除失败，请重试！", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除发生错误", "错误提示");
            }
        }

        /// <summary>
        /// 恢复配方
        /// </summary>
        /// <param name="model"></param>
        private void RecoverRecipe(RecipesModel model)
        {
            try
            {
                List<int> selectedRecipeIds = new List<int>();
                selectedRecipeIds.Add(model.RecipeId);
                if (recipesBLL.RecoverRecipe(selectedRecipeIds))
                {
                    LoadRecipesData();
                }
                else
                {
                    MessageBox.Show("恢复配方发生错误！请重试！", "错误提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("恢复配方发生错误！请重试！", "错误提示");
            }
           
        }

        /// <summary>
        /// 展示配方信息页面（0常看详情、 1编辑、2新增）
        /// </summary>
        /// <param name="actType"></param>
        /// <param name="recipeId"></param>
        private void ShowRecipeInfoForm(int actType,int recipeId)
        { 
            RecipeInfoForm recipeInfoForm = new RecipeInfoForm();
            recipeInfoForm.Tag = new AddOrUpdateModel() 
            { 
                ActType = actType, 
                FId = recipeId 
            };
            recipeInfoForm.ReLoadList += () => LoadRecipesData();
            recipeInfoForm.ShowDialog();
        }

        /// <summary>
        /// 新增按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_insert_Click(object sender, EventArgs e)
        {
            ShowRecipeInfoForm(2, 0);
        }
    }
}
